package com.rapida.plugin;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.rapida.framwork.RapidActivity;
import com.rapida.framwork.RapidaLog;

import java.io.File;
import java.lang.reflect.Constructor;
import java.util.List;

import dalvik.system.DexClassLoader;
import dalvik.system.PathClassLoader;

public abstract class RapidPluginActivity extends RapidActivity {
	private PluginManager mPluginManager;
	private PluginImpl mPluginImpl = new PluginImpl();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mPluginManager = PluginManager.get(getBaseContext());
		mPluginManager.searchPlugin();
		super.onCreate(savedInstanceState);
		for (PluginInfo pi : mPluginManager.getPluginInfo()) {
			try {
				final String pluginPath = pi.pluginPath;
				final String pluginEntry = pi.pluginEntry;
				mPluginImpl.registerPlugin(new IPlugin.PluginAgent() {
					@Override
					public int getPluginId() {
						return mPluginImpl.nextId();
					}

                    @Override
					public PluginController createPlugin() throws Exception {
						File targetDex = getApplicationContext().getDir("dex", 0);
						String targetDexPath = targetDex.getAbsolutePath();
						DexClassLoader dexClassLoader = new DexClassLoader(pluginPath, targetDexPath, null, getClassLoader());
						Class<?> localClass = dexClassLoader.loadClass(pluginEntry);
						return  (PluginController) localClass.newInstance();
					}
				});
			} catch (Exception e) {
				RapidaLog.e("registerPlugin exception()");
			}
		}
	}

    public PluginImpl getPluginImpl() {
        return mPluginImpl;
    }

    public List<PluginInfo> getPlugins() {
        return mPluginManager.getPluginInfo();
    }
}
